<template>
  <div class="app-container" v-loading="isLoading">
    <div class="w-map" id="security-cesium-map"></div>
  </div>
</template>

<script>
import { cesiumToken } from "@/utils/use-g-map";
import { detAirport, putAirport } from "@/api/cruise/airdrome";
import { uploadPlanImg } from "@/api/command/plan";
import { createUniqueString } from "@/utils/index";
import html2canvas from "html2canvas";
import { getProviderViewModels } from "@/utils/cesium/provider.js";
import { We, Fe } from "@/utils/cesium/funcs.js";
import {
  tiandiVec_w,
  tiandiVav_w,
  tiandiImg_w,
  tiandiCia_w,
} from "@/utils/cesium/tiandiLayer.js";
export default {
  data() {
    return {
      viewer: null, // 地图实例
      helper: null, // 地图事件监听器
      zoom: 10,
      placeSearch: null, // 存放地图搜索对象
      isShowAddressSearch: false, //是否显示搜索
      addressSearch: "", // 地址选择
      addressOptions: [], // 地址搜索列表
      addressSearchLoading: false, // 地址搜索加载
      addressMarker: null, // 搜索到地址的点位对象
      isaddLayer: false,
      satellite: null, //卫星图层
      detData: {},
      sector: {
        areaNum: 8, // 区域数量
        tilt: 10, // 倾斜角
        height: 150, // 默认高度
        areaList: [
          { areaName: "A区", radius: 3000 },
          { areaName: "B区", radius: 4000 },
          { areaName: "C区", radius: 5000 },
          { areaName: "D区", radius: 2000 },
          { areaName: "E区", radius: 1000 },
          { areaName: "F区", radius: 3500 },
          { areaName: "G区", radius: 3000 },
          { areaName: "H区", radius: 4000 },
        ],
        constructAreaList: [], // 超高建筑点位
      },
      customLayer: null, // 安全区域图层
      fanCanvas: null, // 安全区域canvas
      isDrawGon: false, // 是否开启超高建筑绘画
      isAddMarker: false,
      faceMarker: [], //超高建筑实例
      activeGonObj: {
        area: 0,
        color: "#627bf2",
        lat: 0,
        lng: 0,
        id: "",
        pathList: [],
        height: 500,
      },
      isScreenshot: false, //图片是否上传完成
      timer: null,
      isLoading: false,
    };
  },
  methods: {
    initMap() {
      let _this = this;
      // let [tiandiVecModel, tiandiImgModel] = getProviderViewModels();
      Cesium.Ion.defaultAccessToken = cesiumToken;
      // 渲染cesium
      this.viewer = new Cesium.Viewer("security-cesium-map", {
        // imageryProviderViewModels: [tiandiImgModel,tiandiVecModel],
        geocoder: true, //搜索框
        animation: false, //左下角的动画控件的显示
        shouldAnimate: false, //控制模型动画
        timeline: false, //底部的时间轴
        fullscreenButton: false, //右下角的全屏按钮
        selectionIndicator: true, //选择指示器
        homeButton: false,
        infoBox: false, //信息面板
        baseLayerPicker: false, //图层选择按钮
        navigationHelpButton: false, //右上角的帮助按钮
        sceneModePicker: false, //3d/2d 模式切换按钮
        terrainProvider: Cesium.createWorldTerrain({
          requestWaterMask: true,
          requestVertexNormals: true,
        }), // 提供地形 使用Cesium在线Ion地形
        skyBox: false,
        scene3DOnly: true,
        // shouldAnimate: true, // 表示实体是运行状态
      });
      // 添加图层
      this.viewer.imageryLayers.addImageryProvider(tiandiImg_w, 10);
      this.viewer.imageryLayers.addImageryProvider(tiandiCia_w, 10);

      // 设置鼠标滚轮进行视图 zoom 变化
      this.viewer.scene.screenSpaceCameraController.zoomEventTypes = [
        Cesium.CameraEventType.WHEEL,
      ];
      // 设置鼠标右键拖动地图, 允许用户在3D和2.5D模式下倾斜，或者在2D模式下旋转的输入
      this.viewer.scene.screenSpaceCameraController.tiltEventTypes = [
        Cesium.CameraEventType.RIGHT_DRAG,
      ];
      this.viewer.scene.screenSpaceCameraController.minimumZoomDistance = 0.8;
      // 开启深度检测
      this.viewer.scene.globe.depthTestAgainstTerrain = true;

      this.viewer._cesiumWidget._creditContainer.style.display = "none"; //隐藏logo版权
      this.viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(
          _this.detData.longitude,
          _this.detData.latitude,
          2000.0
        ),
      });
      this.viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(
          _this.detData.longitude,
          _this.detData.latitude,
          _this.sector.height
        ),
        billboard: {
          image: require("@/assets/images/hezi.png"),
          width: 30, // default: undefined
          height: 30, // default: undefined
          // HeightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
        },
      });
      // console.log(_this.detData.longitude, _this.detData.latitude)
      // let cartographic = Cesium.Cartographic.fromDegrees(_this.detData.longitude, _this.detData.latitude);
      // let height = this.viewer.scene.globe.getHeight(cartographic);
      // console.log("机场位置高度：",height)
      let handler = new Cesium.ScreenSpaceEventHandler(
        _this.viewer.scene.canvas
      );
      handler.setInputAction(function (event) {
        console.log("event", event);

        let ray = _this.viewer.camera.getPickRay(event.position);
        let cartesian1 = _this.viewer.scene.globe.pick(ray, _this.viewer.scene);
        console.log("世界坐标", cartesian1);

        let cartographic1 = Cesium.Cartographic.fromCartesian(cartesian1);
        let lng1 = Cesium.Math.toDegrees(cartographic1.longitude); // 经度
        let lat1 = Cesium.Math.toDegrees(cartographic1.latitude); // 纬度
        let alt1 = cartographic1.height; // 高度
        let coordinate = {
          longitude: Number(lng1.toFixed(6)),
          latitude: Number(lat1.toFixed(6)),
          altitude: Number(alt1.toFixed(2)),
        };

        console.log("获取加载地形后的经纬度(弧度)和高程", coordinate);

        let earthPosition = _this.viewer.scene.pickPosition(event.position);
        if (Cesium.defined(earthPosition)) {
          let cartographic1 = Cesium.Cartographic.fromCartesian(earthPosition);
          let lon1 = Cesium.Math.toDegrees(cartographic1.longitude).toFixed(5);
          let lat1 = Cesium.Math.toDegrees(cartographic1.latitude).toFixed(5);
          let height1 = cartographic1.height.toFixed(2);
          console.log(earthPosition, { lon: lon1, lat: lat1, height: height1 });
        }

        var pick = new Cesium.Cartesian2(event.position.x, event.position.y);
        if (pick) {
          var cartesian = _this.viewer.scene.globe.pick(
            _this.viewer.camera.getPickRay(pick),
            _this.viewer.scene
          );
          if (cartesian) {
            //世界坐标转地理坐标（弧度）
            var cartographic =
              _this.viewer.scene.globe.ellipsoid.cartesianToCartographic(
                cartesian
              );
            if (cartographic) {
              //海拔
              var height = _this.viewer.scene.globe.getHeight(cartographic);
              //视角海拔高度
              var he = Math.sqrt(
                _this.viewer.scene.camera.positionWC.x *
                  _this.viewer.scene.camera.positionWC.x +
                  _this.viewer.scene.camera.positionWC.y *
                    _this.viewer.scene.camera.positionWC.y +
                  _this.viewer.scene.camera.positionWC.z *
                    _this.viewer.scene.camera.positionWC.z
              );
              var he2 = Math.sqrt(
                cartesian.x * cartesian.x +
                  cartesian.y * cartesian.y +
                  cartesian.z * cartesian.z
              );
              //地理坐标（弧度）转经纬度坐标
              var point = [
                (cartographic.longitude / Math.PI) * 180,
                (cartographic.latitude / Math.PI) * 180,
              ];
              if (!height) {
                height = 0;
              }
              if (!he) {
                he = 0;
              }
              if (!he2) {
                he2 = 0;
              }
              if (!point) {
                point = [0, 0];
              }

              console.log(
                "海拔高度:",
                height.toFixed(2),
                "经度:",
                point[0].toFixed(6),
                "纬度:",
                point[1].toFixed(6)
              );
              // coordinatesDiv.innerHTML = "<span id='cd_label' style='font-size:13px;text-align:center;font-family:微软雅黑;color:#edffff;'>视角高度:" + (he - he2).toFixed(2) + "米&nbsp;&nbsp;&nbsp;&nbsp;海拔高度:" + height.toFixed(2) + "米&nbsp;&nbsp;&nbsp;&nbsp;经度：" + point[0].toFixed(6) + "&nbsp;&nbsp;纬度：" + point[1].toFixed(6) + "</span>";
            }
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      // const scene = _this.viewer.scene;
      // const ellipsoid = scene.globe.ellipsoid;
      // const position = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
      // const handler1 = new Cesium.ScreenSpaceEventHandler(scene.canvas);
      // handler1.setInputAction(function(movement) {
      //     console.log("movement",movement)
      //     let ray = _this.viewer.camera.getPickRay(movement.endPosition);
      //     let cartesian1 = _this.viewer.scene.globe.pick(ray, _this.viewer.scene);

      //     console.log(Cesium.SceneTransforms.wgs84ToWindowCoordinates(scene, cartesian1));
      // }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
    // 获取安全设置详情
    getData() {
      let _this = this;
      detAirport(this.$route.params.id).then((res) => {
        console.log("机场详情", res);
        this.detData = res.data;
        // _this.zoom = 13
        // this.map.setZoomAndCenter(_this.zoom,[_this.detData.longitude,_this.detData.latitude])
        if (this.detData.sector) {
          this.sector = JSON.parse(this.detData.sector);
          // console.log("this.sector",this.sector)
        }
        this.initMap();
        // this.drawFan(_this.detData.longitude,_this.detData.latitude,-90 + Number(_this.sector.tilt), 360/_this.sector.areaNum,_this.sector.areaList)
        // this.loadAllGon()
        // var icon = new AMap.Icon({
        //     size: new AMap.Size(30, 30),
        //     image: require("@/assets/images/hezi.png"),
        //     imageSize: new AMap.Size(30, 30),
        //     imageOffset: new AMap.Pixel(0, 0),
        // });
        // let marker = new AMap.Marker({
        //     position: [_this.detData.longitude,_this.detData.latitude],
        //     icon: icon,
        //     offset: new AMap.Pixel(-15, -15),
        //     draggable: false,
        //     zIndex: 9999,
        // });
        // _this.map.add(marker)
      });
    },
  },
  mounted() {
    this.getData();
  },
  beforeDestroy() {
    // console.log("this.helper",this.helper)
    // if(this.helper){
    //     this.helper.removeAll()
    //     this.helper = null
    // }
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background: #f5f5f5;
  position: relative;
}
.w-map {
  width: 100%;
  height: 100%;
  border-radius: 10px;
  overflow: hidden;
  border: 1px solid rgba(73, 68, 78, 0.2);
}
</style>
